<template>
  <div class="p-16px">
    <el-card>
      <el-button type="primary" @click="handleAdd">添加货道模板</el-button>
    </el-card>
    <el-card class="mt-16px">
      <el-table :data="tableData" v-loading="loading">
        <el-table-column type="index" width="80" label="编号" />
        <el-table-column prop="deviceTypeName" label="设备类型" />
        <el-table-column prop="freightRoadName" label="模板名称" />
        <el-table-column prop="createTime" label="添加时间" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="handleDetail(row)">
              详情
            </el-button>
            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-16px flex justify-end">
        <el-pagination
          v-model:currentPage="params.current"
          v-model:page-size="params.size"
          layout="prev, pager, next"
          background
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog v-model="dialogVisible" title="货道模板" width="800px">
      <el-form :model="form">
        <el-form-item label="模板名称" prop="freightRoadName">
          <el-input v-model="form.freightRoadName" :disabled="isDisabled" />
        </el-form-item>
        <div class="tmeplate-list">
          <div
            class="flex items-center pl-16px"
            v-for="(item, index) in templateList"
            :key="index"
          >
            <view class="mr-16px text-24px">{{ index + 1 }}</view>
            <view
              class="item flex items-center justify-center text-20px"
              v-for="(deep, i) in item"
              :key="i"
              @click="handleEditFreightDeep(index, i)"
            >
              {{ deep }}
            </view>
            <div class="ml-16px">
              <el-button
                v-if="item.length < 10 && !isDisabled"
                type="success"
                icon="Plus"
                @click="handleAddTemplateChild(index)"
              ></el-button>
              <el-button
                v-if="item.length > 1 && !isDisabled"
                type="danger"
                icon="Minus"
                @click="handleDeleteTemplateChild(index)"
              ></el-button>
            </div>
          </div>
          <div
            class="mt-16px ml-60px"
            v-if="templateList.length < 10 && !isDisabled"
          >
            <el-button
              type="success"
              icon="Plus"
              @click="handleAddTemplate"
            ></el-button>
          </div>
        </div>
        <el-form-item class="mt-32px w-full" v-if="!isDisabled">
          <div class="flex justify-end w-full pr-32px">
            <el-button
              type="primary"
              class="w-80px"
              @click="handleSave"
              :loading="submitLoading"
            >
              保存
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="dialogFreightDeep" title="货道深度" width="800px">
      <el-form :model="formFreightDeep">
        <el-form-item label="货道深度" prop="freightDeep">
          <el-input-number
            v-model="formFreightDeep"
            :min="1"
            :max="100"
            :disabled="isDisabled"
          />
        </el-form-item>
        <el-form-item v-if="!isDisabled">
          <el-button type="primary" @click="handleSaveFreightDeep">
            保存
          </el-button>
          <el-button @click="dialogFreightDeep = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useCommonStoreHook } from "@/store/modules/common";
import dayjs from "dayjs";
// 默认货道深度
const defaultFreightDeep = 15;

const commonStore = useCommonStoreHook();
const selectedIndex = ref([0, 0]);
const dialogFreightDeep = ref(false);
const formFreightDeep = ref(defaultFreightDeep);
const tableData = ref([]);
const defaultForm = {
  deviceType: "",
  freightRoadName: "",
};
const submitLoading = ref(false);
const templateList = ref([[15]]);
const form = ref({ ...defaultForm });
const isDisabled = computed(() => form.value.id);
const dialogVisible = ref(false);
const params = ref({
  current: 1,
  size: 10,
  freightRoadName: "",
});
const total = ref(0);
const loading = ref(false);
const handleAdd = () => {
  form.value = { ...defaultForm };
  dialogVisible.value = true;
};
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "删除中...";
        commonStore
          .delFreightRoadTemplate({ id: row.id })
          .then(() => {
            done();
            ElMessage.success("删除成功");
            fetchTemplateList();
          })
          .finally(() => {
            instance.confirmButtonLoading = false;
            instance.confirmButtonText = "确定";
          });
      } else {
        done();
      }
    },
  }).then(() => {
    console.log("删除货道模板", row);
  });
};
const handleSaveFreightDeep = () => {
  const [index, i] = selectedIndex.value;
  templateList.value[index][i] = formFreightDeep.value;
  dialogFreightDeep.value = false;
};
const handleEditFreightDeep = (index, i) => {
  selectedIndex.value = [index, i];
  formFreightDeep.value = templateList.value[index][i];
  dialogFreightDeep.value = true;
};
const handleAddTemplate = () => {
  templateList.value.push([defaultFreightDeep]);
};
const handleAddTemplateChild = (index) => {
  console.log(index);

  templateList.value[index] = templateList.value[index].concat([
    defaultFreightDeep,
  ]);
};
const handleDeleteTemplateChild = (index) => {
  templateList.value[index] = templateList.value[index].slice(0, -1);
  if (templateList.value[index].length < 1) {
    templateList.value.splice(index, 1);
  }
};
const handleSave = () => {
  console.log(form.value);
  const freightArrayList = templateList.value.map((item) => item.length);
  const freightUnitList = templateList.value.map((item) =>
    item.map((deep) => ({ roadUnitCapacity: deep }))
  );
  submitLoading.value = true;
  commonStore
    .addFreightRoadTemplate({
      freightArrayList,
      freightUnitList,
      freightRoadName: form.value.freightRoadName,
    })
    .then(() => {
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      fetchTemplateList();
      submitLoading.value = false;
    })
    .finally(() => {
      submitLoading.value = false;
    });
};
const handleDetail = (row) => {
  commonStore.getFreightRoadTemplateDetail({ id: row.id }).then((res) => {
    form.value = { ...res };
    const freightArrayList = JSON.parse(res.freightArrayList).map((item) =>
      new Array(item).fill(defaultFreightDeep)
    );
    templateList.value = freightArrayList.map((item, index) =>
      item.map((deep, i) => res.freightUnitList[index][i].roadUnitCapacity)
    );
    dialogVisible.value = true;
  });
};
const handleCurrentChange = (current) => {
  params.value.current = current;
  fetchTemplateList();
};
const fetchTemplateList = () => {
  loading.value = true;
  commonStore
    .queryFreightRoadTemplatePage(params.value)
    .then((res) => {
      tableData.value = res.records.map((item) => ({
        ...item,
        createTime: dayjs(item.createTime).format("YYYY-MM-DD HH:mm:ss"),
      }));
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleSearch = () => {
  params.value.current = 1;
  fetchTemplateList();
};

onMounted(() => {
  handleSearch();
});
</script>

<style lang="scss" scoped>
.tmeplate-list {
  .item {
    cursor: pointer;
    width: 50px;
    height: 50px;
    background-color: #f0f0f0;
    border-radius: 50%;
    margin: 10px;
  }
}
</style>
